package model

import (
	"fmt"
	"github.com/go-redis/redis"
	"sync"
	"time"
)

const (
	TOKEN_PREFIX = "refresh_token_"
	TOKEN_EXPIRE = time.Hour*24*3
)

var (
	blog_redis      *redis.Client
	blog_redis_once sync.Once
)

func createRedisClient(address, password string, db int) *redis.Client {
	client := redis.NewClient(&redis.Options{
		Addr:     address,
		Password: password,
		DB:       db,
	})
	if err := client.Ping().Err(); err != nil {
		panic(fmt.Errorf("conncet to redis %d failed: %v", db, err))
	} else {
		fmt.Println("conncet to redis db: ", db)
	}
	return client
}

func GetRedisClient() *redis.Client {
	blog_redis_once.Do(func() {
		if blog_redis == nil {
			blog_redis = createRedisClient("127.0.0.1:6379", "", 0)
		}
	})
	return blog_redis
}


func SetToken(refreshToken, authToken string) error {
	client:=GetRedisClient()
	err:=client.Set(TOKEN_PREFIX+refreshToken, authToken, TOKEN_EXPIRE).Err()
	if err!=nil{
		fmt.Errorf("write token pair(%s, %s) to redis failed: %v",
			refreshToken, authToken, err)
		return err
	}
	return nil
}

func GetToken(refreshToken string) string {
	client:=GetRedisClient()
	authtoken, err:=client.Get(TOKEN_PREFIX+refreshToken).Result()
	if err!=nil{
		if err!=redis.Nil {
			fmt.Errorf("get authToken of refreshToken %s failed: %v", refreshToken, err)
		}
	}
	return authtoken
}
